package com.bingqing.service;



import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bingqing.dao.BookDao;
import com.bingqing.dao.TypeDao;
import com.bingqing.entity.Book;
import com.bingqing.entity.Params;
import com.bingqing.entity.Type;
import com.bingqing.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: AdminService
 * Package: com.bingqing.springboot.service
 * Description:
 *
 * @Author liuyujie
 * @Create 2024-03-06 13:46
 * @Version 1.0
 */
@Service
public class BookService {
    @Resource
    BookDao bookDao;

    @Resource
    TypeDao typeDao;

    public void add(Book book) {
        bookDao.insertSelective(book);
    }

    public void update(Book book) {
        bookDao.updateByPrimaryKeySelective(book);
    }

    public void deleteById(Integer id) {
        bookDao.deleteByPrimaryKey(id);
    }


    public PageInfo<Book> findBySearch(Params params) {
        PageHelper.startPage(params.getPageNum(),params.getPageSize());
        List<Book> list = bookDao.findBySearch(params);
        //1.判断list是否为空
        if(CollUtil.isEmpty(list)){
            return PageInfo.of(new ArrayList<>());
        }
        //2.遍历list,根据每个book的typeId从type表中查出type对象，取name赋值给book的typeName
        for (Book book : list) {
           if(ObjectUtil.isNotEmpty(book.getTypeId())){
               Type type = typeDao.selectByPrimaryKey(book.getTypeId());
               book.setTypeName(type.getName());
           }
        }
        return PageInfo.of(list);
    }

    public List<Book> findAll() {
        return bookDao.findAll();
    }
}
